//
//  DeliveryAddress.m
//  bestkeep
//
//  Created by bj on 2016/11/4.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BK_my_ShippingAddressVC.h"
#import "Masonry.h"
#import "BK_my_ShippingAddressCell.h"
#import "BKMyCommon.h"
#import "BK_my_ShippingAddress.h"
#import "BK_my_EditAddressVC.h"
#import "BK_my_ShippingAddressServer.h"
#import "ExceptionView.h"

@interface BK_my_ShippingAddressVC ()<UITableViewDelegate, UITableViewDataSource, clickButtonDelegate, UIAlertViewDelegate>

@property (nonatomic, strong) UITableView *shippingAddressTableView;
@property (nonatomic, strong) UIButton *addAddressButton;
@property (nonatomic, strong) NSMutableArray *shippingAddressArray;

@property (nonatomic, strong) BK_my_ShippingAddress *shippingAddress;
@property (nonatomic) BOOL isDefaultAddress;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIView *backindicatorView;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic, strong) ExceptionView *exceptionView;
@end

@implementation BK_my_ShippingAddressVC

static NSString *shippingAddressCell = @"shippingAddressCell";

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self shippingAddressList];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [HUD dismiss];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    self.shippingAddressArray = [[NSMutableArray alloc] init];
}

- (void)createUI{
    
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.title = @"收货地址管理";
    self.view.backgroundColor = RGBCOLOR(238, 238, 238, 1);
    
    
    if (_shippingAddressTableView == nil) {
        self.shippingAddressTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        self.shippingAddressTableView.backgroundColor = [UIColor clearColor];
        self.shippingAddressTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.shippingAddressTableView.delegate = self;
        self.shippingAddressTableView.dataSource = self;
    }
    [self.shippingAddressTableView registerClass:[BK_my_ShippingAddressCell class] forCellReuseIdentifier:shippingAddressCell];
    [self.view addSubview:self.shippingAddressTableView];
    [self tableViewConstraints:0];
    
    /*
     * 导航栏右边添加地址按钮
     */
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addAddressClick)];
    rightItem.tintColor = [UIColor blackColor];
    
    self.navigationItem.rightBarButtonItem = rightItem;
}



- (void)tableViewConstraints:(NSInteger)integer {
    [self.shippingAddressTableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.view.mas_bottom).mas_offset(integer);
    }];
}

-(void)checkNetWorking {
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            [self loadShippingAddressList];
        }
            break;
            
        default: {
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self shippingAddressList];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
        }
            break;
    }
}

- (void)loadShippingAddressList {
    [BK_my_ShippingAddressServer shippingAddressList:^(id obj, NSError *error) {
        if (error) {
            if(!self.exceptionView && error) {
                self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeServerError];

                
                
                ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:ExceptionCodeTypeServerError handler:^(ExceptionViewAction *action) {
                    [self startAnimationInView];
                    [self.exceptionView dismiss];
                    self.exceptionView = nil;
                    [self shippingAddressList];
                }];
                [self.exceptionView addAction:retryAction];
                [self.exceptionView showInView:self.view];
                [HUD dismiss];
                [self stopAnimationInView];
            }
        } else {
            [self stopAnimationInView];
            if(self.exceptionView) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
            }
            if ([obj isKindOfClass:[NSDictionary class]]) {
                [HUD showMessage:obj[@"msg"]];
            } else {
                self.shippingAddressArray = (NSMutableArray *)obj;
                [self.shippingAddressTableView reloadData];
                self.shippingAddressTableView.tableFooterView = [self creatFooterView];
                if (self.shippingAddressArray.count != 0) {
                    [HUD dismiss];
                } else {
                    [HUD showMessage:@"暂无收货地址"];
                }
            }
        }
    }];
}

//收货地址列表
- (void)shippingAddressList {
    [self checkNetWorking];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.shippingAddressArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section < 2) {
        return 5;
    }
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.0001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 132;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BK_my_ShippingAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:shippingAddressCell];
    if (cell == nil) {
        cell = [[BK_my_ShippingAddressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:shippingAddressCell];
    }
    cell.addressButtonDelegate = self;
    [cell updateCellInformation:self.shippingAddressArray[indexPath.section]];
    return cell;
}



- (void)setDefaultAddress:(BK_my_ShippingAddress *)address {
    NSString *addressId = address.shippingAddressID;
    __weak typeof(self)weakSelf = self;
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:addressId, @"deliver_id", nil];
   [BK_my_ShippingAddressServer setDefaultAddress:dict :^(id obj, NSError *error) {
       NSString *success = obj[@"success"];
       if ([success integerValue] == 1) {
           [HUD showSuccessMessage:@"设置默认地址成功"];
           [weakSelf shippingAddressList];
           [self stopAnimationInView];
       } else {
           [self stopAnimationInView];
           [HUD showMessage:@"设置默认地址失败"];
       }
    }];
}

- (void)clickDelegateAddress:(BK_my_ShippingAddress *)address {
    _shippingAddress = address;
    if (self.shippingAddressArray.count == 1) {
        [HUD showMessage:@"最后地址不能删除"];
        return;
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确认删除？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString *btnTitle = [alertView buttonTitleAtIndex:buttonIndex];
    if ([btnTitle isEqualToString:@"确定"]) {
        [self deleteShippingAddress:self.shippingAddress];
    }
}

//删除收货地址
- (void)deleteShippingAddress:(BK_my_ShippingAddress *)address {
    [self startAnimationInView];
    __weak typeof(self)weakSelf = self;
    NSString *addressId = address.shippingAddressID;
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:addressId, @"deliver_id", nil];
    
    [BK_my_ShippingAddressServer deleteShippingAddress:dict :^(id obj, NSError *error) {
        NSString *success = obj[@"success"];
        if ([success integerValue] == 1) {
            [HUD showSuccessMessage:@"删除地址成功"];
            if (address.isDefaultAddress) {
                [self stopAnimationInView];
                [weakSelf.shippingAddressArray removeObjectAtIndex:0];
                _isDefaultAddress = 1;
                [weakSelf setDefaultAddress:[weakSelf.shippingAddressArray firstObject]];
            } else {
                [weakSelf shippingAddressList];
            }
        } else {
            [self stopAnimationInView];
            [HUD showMessage:@"删除地址失败"];
        }
    }];
}
//设置默认收货地址
- (void)clickSetAddressCell:(BK_my_ShippingAddressCell *)cell selectedButton:(UIButton *)selectedButton {
    if (cell.isDefault == NO) {
        [self startAnimationInView];
        cell.datas.isDefaultAddress = !cell.isDefault;
        [self setDefaultAddress:cell.datas];
        [self.shippingAddressTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    } else {
        [HUD showMessage:@"默认地址不能为空"];
    }
}



//编辑收货地址
- (void)clickEditAddressButton:(UIButton *)click addressModel:(BK_my_ShippingAddress *)address :(BK_my_ShippingAddressCell *)cell {
    BK_my_EditAddressVC *editVC = [[BK_my_EditAddressVC alloc] init];
    editVC.address = address;//有数据
    editVC.isShowSwitch = !cell.isDefault;
    [self.navigationController pushViewController:editVC animated:YES];
}

//添加收货地址
- (void)addAddressClick {
    BK_my_EditAddressVC *vc = [[BK_my_EditAddressVC alloc] init];
    vc.isAddShippingAddress = YES;//从新增进地址按钮来
    vc.isShowSwitch = YES;//显示switch
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)startAnimationInView {
    _backindicatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64)];
    _backindicatorView.backgroundColor = [UIColor clearColor];
    [self.view.window addSubview:_backindicatorView];
    _indicatorView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 70, 70)];
    _indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [_indicatorView setCenter:CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2)];
    _indicatorView.color = RGBCOLOR(42, 187, 155, 1);
    _indicatorView.backgroundColor = [UIColor clearColor];
    _indicatorView.alpha = 1.0;
    CGAffineTransform transform = CGAffineTransformMakeScale(1.5f, 1.5f);
    _indicatorView.transform = transform;
    [_backindicatorView addSubview:_indicatorView];
    [_indicatorView startAnimating];
}

- (void)stopAnimationInView {
    [_indicatorView stopAnimating];
    [_indicatorView removeFromSuperview];
    [_backindicatorView removeFromSuperview];
}
#pragma mark==================footer==================
- (UIView *)creatFooterView {
    _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 80)];
    _footerView.backgroundColor = RGBCOLOR(238, 238, 238, 1);
    self.addAddressButton = [[UIButton alloc] initWithFrame:CGRectMake(15, 16, ScreenWidth - 30, 48)];
    self.addAddressButton.backgroundColor = BK_MY_COLOR_01;
    self.addAddressButton.layer.cornerRadius = 5.0;
    self.addAddressButton.titleLabel.font = [UIFont systemFontOfSize:18.0];
    [self.addAddressButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.addAddressButton setTitle:@"+新增收货地址" forState:UIControlStateNormal];
    [_footerView addSubview:self.addAddressButton];
    [self.addAddressButton addTarget:self action:@selector(addAddressClick) forControlEvents:UIControlEventTouchUpInside];
    return _footerView;
}
@end
